<template>
  <div class="employee-management">
    <div class="header">
      <h2>员工管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增员工
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" inline>
        <el-form-item label="员工姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入员工姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="searchForm.deptId"
            placeholder="请选择部门"
            clearable
            style="width: 200px"
            :loading="deptLoading"
          >
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="在职状态">
          <el-select
            v-model="searchForm.workState"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="休假" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="员工姓名" min-width="120" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="idNumber" label="身份证号" min-width="180" />
        <el-table-column prop="deptName" label="部门" min-width="120" />
        <el-table-column prop="position" label="职位" min-width="120" />
        <el-table-column prop="jobLevel" label="职级" min-width="100" />
        <el-table-column prop="hireDate" label="入职日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.hireDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="workState" label="在职状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getWorkStateType(row.workState)">
              {{ getWorkStateText(row.workState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" min-width="120" />
        <el-table-column prop="contactEmail" label="邮箱" min-width="150" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="handleUpdateStatus(row)"
                :loading="statusLoading === row.id"
              >
                状态变更
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(row)"
                :loading="deleteLoading === row.id"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <EmployeeFormDialog
      v-model="dialogVisible"
      :form-data="currentEmployee"
      :department-options="departmentOptions"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />

    <!-- 状态变更对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="状态变更"
      width="400px"
      :before-close="handleStatusDialogClose"
    >
      <div class="status-dialog-content">
        <p class="employee-info">员工：<strong>{{ currentStatusEmployee.name }}</strong></p>
        <p class="current-status">当前状态：<el-tag :type="getWorkStateType(currentStatusEmployee.workState)">{{ getWorkStateText(currentStatusEmployee.workState) }}</el-tag></p>
        
        <el-form :model="statusForm" label-width="80px">
          <el-form-item label="新状态" prop="workState">
            <el-select
              v-model="statusForm.workState"
              placeholder="请选择新状态"
              style="width: 100%"
            >
              <el-option label="在职" :value="1" />
              <el-option label="离职" :value="2" />
              <el-option label="休假" :value="3" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleStatusDialogClose" :disabled="statusLoading">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleStatusConfirm"
            :loading="statusLoading"
            :disabled="!statusForm.workState || statusForm.workState === currentStatusEmployee.workState"
          >
            {{ statusLoading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { employeeApi } from '@/api/employee'
import { deptApi } from '@/api/dept'
import EmployeeFormDialog from './components/EmployeeFormDialog.vue'

// 响应式数据
const loading = ref(false)
const deptLoading = ref(false)
const deleteLoading = ref(null)
const statusLoading = ref(null)
const dialogVisible = ref(false)
const statusDialogVisible = ref(false)
const isEdit = ref(false)
const currentEmployee = ref({})
const currentStatusEmployee = ref({})

// 搜索表单
const searchForm = reactive({
  name: '',
  deptId: null,
  workState: null
})

// 状态变更表单
const statusForm = reactive({
  workState: null
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 部门选项 - 从API获取
const departmentOptions = ref([])

// 生命周期
onMounted(() => {
  loadDepartmentOptions()
  loadEmployeeList()
})

// 加载部门选项
const loadDepartmentOptions = async () => {
  try {
    deptLoading.value = true
    const response = await deptApi.getDeptList()
    
    if (response && response.code === 1) {
      departmentOptions.value = response.data || []
    } else {
      ElMessage.error(response?.msg || '获取部门列表失败')
      departmentOptions.value = []
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败，请稍后重试')
    departmentOptions.value = []
  } finally {
    deptLoading.value = false
  }
}

// 加载员工列表
const loadEmployeeList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    
    // 清理空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await employeeApi.getEmployeeList(params)
    
    if (response && response.code === 1) {
      tableData.value = response.data.rows || response.data
      pagination.total = response.data.total
    } else {
      ElMessage.error(response?.msg || '获取员工列表失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadEmployeeList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    deptId: null,
    workState: null
  })
  pagination.page = 1
  loadEmployeeList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadEmployeeList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  loadEmployeeList()
}

// 新增员工
const handleAdd = () => {
  isEdit.value = false
  currentEmployee.value = {
    name: '',
    gender: 1,
    idNumber: '',
    deptId: null,
    position: '',
    jobLevel: '',
    hireDate: '',
    workState: 1,
    contactPhone: '',
    contactEmail: '',
    avatar: ''
  }
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  isEdit.value = true
  currentEmployee.value = { ...row }
  dialogVisible.value = true
}

// 打开状态变更对话框
const handleUpdateStatus = (row) => {
  currentStatusEmployee.value = { ...row }
  statusForm.workState = row.workState // 默认选中当前状态
  statusDialogVisible.value = true
}

// 状态变更确认
const handleStatusConfirm = async () => {
  try {
    statusLoading.value = currentStatusEmployee.value.id
    
    const oldStateText = getWorkStateText(currentStatusEmployee.value.workState)
    const newStateText = getWorkStateText(statusForm.workState)
    
    // 如果状态没有变化，直接关闭对话框
    if (statusForm.workState === currentStatusEmployee.value.workState) {
      ElMessage.warning('状态未发生变化')
      handleStatusDialogClose()
      return
    }
    
    const response = await employeeApi.updateEmployeeStatus(
      currentStatusEmployee.value.id, 
      statusForm.workState
    )
    
    if (response.code === 1) {
      ElMessage.success(`员工状态已从【${oldStateText}】变更为【${newStateText}】`)
      handleStatusDialogClose()
      loadEmployeeList()
    } else {
      ElMessage.error(response.msg || '更新员工状态失败')
    }
  } catch (error) {
    console.error('状态变更失败:', error)
    ElMessage.error('操作失败')
  } finally {
    statusLoading.value = null
  }
}

// 关闭状态变更对话框
const handleStatusDialogClose = () => {
  statusDialogVisible.value = false
  // 延迟重置表单
  setTimeout(() => {
    currentStatusEmployee.value = {}
    statusForm.workState = null
  }, 300)
}

// 删除员工
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除员工 "${row.name}" 吗？此操作不可恢复！`,
      '警告',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    deleteLoading.value = row.id
    
    const response = await employeeApi.deleteEmployee(row.id)
    
    if (response.code === 1) {
      ElMessage.success('删除员工成功')
      // 如果删除的是当前页的最后一条数据，需要跳转到上一页
      if (tableData.value.length === 1 && pagination.page > 1) {
        pagination.page -= 1
      }
      loadEmployeeList()
    } else {
      ElMessage.error(response.msg || '删除员工失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  } finally {
    deleteLoading.value = null
  }
}

// 对话框操作成功
const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadEmployeeList()
}

// 格式化日期（修正版）
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    let date
    if (typeof dateString === 'string') {
      if (dateString.includes('T')) {
        // ISO 格式：2025-10-31T16:03:13
        date = new Date(dateString)
      } else if (dateString.includes(' ')) {
        // 空格分隔格式：2025-10-31 16:03:13
        date = new Date(dateString.replace(' ', 'T'))
      } else {
        // 纯日期格式：2025-10-31
        date = new Date(dateString)
      }
    } else {
      date = new Date(dateString)
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateString
  }
}

// 格式化日期时间（修正版）
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  try {
    let date
    if (typeof dateString === 'string') {
      if (dateString.includes('T')) {
        // ISO 格式：2025-10-31T16:03:13
        date = new Date(dateString)
      } else if (dateString.includes(' ')) {
        // 空格分隔格式：2025-10-31 16:03:13
        date = new Date(dateString.replace(' ', 'T'))
      } else {
        // 其他格式
        date = new Date(dateString)
      }
    } else {
      date = new Date(dateString)
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (e) {
    console.error('日期时间格式化错误:', e)
    return dateString
  }
}

// 获取在职状态文本
const getWorkStateText = (workState) => {
  const stateMap = {
    1: '在职',
    2: '离职',
    3: '休假'
  }
  return stateMap[workState] || '未知'
}

// 获取在职状态标签类型
const getWorkStateType = (workState) => {
  const typeMap = {
    1: 'success',
    2: 'danger',
    3: 'warning'
  }
  return typeMap[workState] || 'info'
}
</script>

<style scoped>
.employee-management {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 状态变更对话框样式 */
.status-dialog-content {
  padding: 10px 0;
}

.employee-info {
  margin-bottom: 15px;
  font-size: 14px;
}

.current-status {
  margin-bottom: 20px;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 10px;
}
</style>